// 使用 React.createClass 创建一个组件

var DemoComponent = React.createClass({
    // 使用 getInitialState 的返回值作为数据的默认值
    getInitialState: function () {
        this.state = {open: false,openQuDao:false};
        return {data: [],tk:this.getUrl(window.location.href).tk,host:"http://app.uyu.com:3001/upload"};
    },

    // 使用 componentDidMount 在组件初始化后执行一些操作
    componentDidMount: function () {
        // 拉取远程数据
        // 开启假数据服务器：
        // cd fake-server && npm install && node applist.js
        var packageName = this.getUrl(window.location.href).package_name;
        this.fetchData(packageName);
    },
    getUrl: function (url) {
        var reg = /([^&?=#]+)=([^&?=#]+)/g;
        var ary = {};
        url.replace(reg, function () {
            ary[arguments[1]] = arguments[2];
        });
        return ary;
    },
    // 使用自定义的 fetchData 方法从远程服务器获取数据
    fetchData: function (packageName) {
        var self = this;
        // 发起 ajax 获取到数据后调用 setState 方法更新组件的数据
        var result = fetch(self.state.host+'/version/getAllVersion?tk='+self.state.tk+'&package_name=' + packageName);

        result.then(function (response) {
            return response.json();
        }).then(function (json) {
            self.setState({data: json.data});
        }).catch(function (ex) {
            console.log('failed', ex)
        });
    },

    onRemove: function (generate) {
        var package_name = generate.package_name;
        var channel_id = generate.channel_id;
        var self = this;
        // 发起 ajax 获取到数据后调用 setState 方法更新组件的数据
        var url = self.state.host+'/version/deleteVersion?tk='+self.state.tk+'&package_name=' + package_name + '&channel_id=' + channel_id;
        fetch(url).then(function (response) {
            return response.json();
        }).then(function (json) {
            if (json.code == 0) {
                self.state.data = self.state.data.filter(function (row, index) {
                    if (row.channel_id != channel_id) {
                        return row;
                    }
                });
                self.setState({data: self.state.data});
            }

        }).catch(function (ex) {
            console.error(ex);
        });
    },
    onUpDataOpen: function (generate) {
        this.setState({open: true,generate:generate});
    },
    onCloseDiv: function () {
        var refs = this.refs;
        React.findDOMNode(refs.open_apk).value='';
        React.findDOMNode(refs.loginContent).value='';
        this.setState({open: false});
    },
    contentLogin: function (keys) {
        var refs = this.refs;
        if(keys=="loginContent"){
            this.setState({loginContent:React.findDOMNode(refs.loginContent).value});
        }else if(keys=="loginContentQuDao"){
            this.setState({loginContentQuDao:React.findDOMNode(refs.loginContentQuDao).value});
        }
    },
    onSureDiv:function(update_info){
        if(update_info != undefined){

            var refs = this.refs;
            var self=this;
            var onSureDiv=React.findDOMNode(refs.onSureDiv);
            onSureDiv.value='上传中';
            onSureDiv.disabled=true;
            onSureDiv.className="open-submit-add";
            var url = self.state.host+"/version/uploadVersion?tk="+self.state.tk;

            var input = React.findDOMNode(refs.open_apk);
            var data = new FormData();

            data.append('apk', input.files[0]);
            data.append("update_info", update_info);
            data.append("channel_id", self.state.generate.channel_id);
            fetch(url,{
                method: "POST",
                body:data
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (json.code == 0) {
                    onSureDiv.value='确认';
                    onSureDiv.disabled=false;
                    onSureDiv.className="open-submit";
                    React.findDOMNode(refs.open_apk).value='';
                    React.findDOMNode(refs.loginContent).value='';




                    var appDatas = self.state.data;
                    for(var i = 0;i<appDatas.length;i++){
                        if(appDatas[i].channel_id == json.data.channel_id){
                            appDatas[i] = json.data;
                            self.setState({data: self.state.data});
                            break;
                        }
                    }
                    self.setState({open: false});
                }else{
                    onSureDiv.value='确认';
                    onSureDiv.disabled=false;
                    onSureDiv.className="open-submit";
                    alert(json.message);
                }
            });
        }else{
            alert("请填写更新说明")
        }

    },
    //qudao
    onCloseDivQuDao:function(){
        var refs = this.refs;
        React.findDOMNode(refs.open_apkQuDao).value='';
        React.findDOMNode(refs.loginContentQuDao).value='';

        this.setState({openQuDao: false});
    },
    onUpDataOpenQuDao: function () {
        this.setState({openQuDao: true});
    },
    onSureDivQuDao:function(update_info_QuDao){
        if(update_info_QuDao != undefined){
            var refs = this.refs;
            var self=this;
            var onSureDivQuDao=React.findDOMNode(refs.onSureDivQuDao);
            onSureDivQuDao.value='上传中';
            onSureDivQuDao.disabled=true;
            onSureDivQuDao.className="open-submit-add";
            var url = self.state.host+"/version/uploadVersion?tk="+self.state.tk;
            var input = React.findDOMNode(refs.open_apkQuDao);
            var data = new FormData();

            data.append('apk', input.files[0]);
            data.append("update_info", update_info_QuDao);
            fetch(url,{
                method: "POST",
                body:data
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (json.code == 0) {
                    onSureDivQuDao.value='确认';
                    onSureDivQuDao.disabled=false;
                    onSureDivQuDao.className="open-submit";
                    React.findDOMNode(refs.open_apkQuDao).value='';
                    React.findDOMNode(refs.loginContentQuDao).value='';



                    var appDatas = self.state.data;
                    appDatas.splice(0,0,json.data);
                    self.setState({data: self.state.data});

                    self.setState({openQuDao: false});
                }else{
                    onSureDivQuDao.value='确认';
                    onSureDivQuDao.disabled=false;
                    onSureDivQuDao.className="open-submit";
                    alert(json.message);

                }
            });
        }else{
            alert("请填写更新说明")
        }
    },
    // 使用 render 方法自动渲染 DOM
    render: function () {
        var self = this;
        var styles = {
            openNew: {position: "absolute", top: "50%", left: "50%", marginLeft: "-300px", marginTop: "-200px", width: "600px", height: "400px", background: "#f9f9f9", border: "1px solid #f90", borderRadius: "10px", color: "#999"},
            openBg:{position:'absolute', width:document.body.clientWidth, height:document.body.clientHeight, background:'#cdcdcd', zIndex:3, overflow:'hidden'}
        };
        var actionUrl="http://192.168.1.109:3000/app/v1/version/uploadVersion?tk=2e192432129d79acf0fceff05ba760a8&update_info="+this.state.loginContent;
        var actionUrlQuDao="http://192.168.1.109:3000/app/v1/version/uploadVersion?tk=2e192432129d79acf0fceff05ba760a8&update_info="+this.state.loginContentQuDao;
        var appGenerate = this.state ? this.state.data.map(function (generate) {
            return (
                <li className="generate-item" key={generate.channel_id}>
                    <span className="generate-dateWidth2">{generate.channel_id}</span>

                    <span className="generate-date generate-dateWidth1">{generate.updated_at}</span>

                    <span className="generate-date generate-dateWidth2">{generate.apk_size}</span>
                    <span className="generate-date generate-dateWidth2">{generate.version_code}</span>
                    <a className="generate-dataPadd" href="#" onClick={self.onRemove.bind(null, generate)}>删除</a>
                    <a className="generate-dataPadd" href="#" onClick={self.onUpDataOpen.bind(null, generate)}>更新</a>
                </li>
            )
        }.bind(this)) : '';// 注意这里 bind(this) 修正了上下文

        return (
            <div>
                <div style={this.state.open?styles.openBg:styles.closeBg}>
                    <div className={this.state.open ? "openDiv" : "closeDiv"} style={styles.openNew}>
                        <div className="open-type">
                            <div className="open-title-box">
                                <h3 className="open-title">自动更新</h3>
                                <span className="open-closeed" onClick={this.onCloseDiv.bind(null)}>关闭</span>
                            </div>
                            <form method="post" encType="multipart/form-data">
                                <table className="open-table">
                                    <tr>
                                        <td className="">
                                            上传apk
                                        </td>
                                        <td>
                                            <input ref='open_apk' type="file" name="apk"/>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="open-upData-login">
                                            填写更新日志
                                        </td>
                                        <td>
                                        <textarea className="open-textarea" name="" ref="loginContent" onChange={this.contentLogin.bind(null,"loginContent")} placeholder="请输入更新日志" id="" rows="10">

                                        </textarea>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="open-upData-login">

                                        </td>
                                        <td className="open-upData-button">
                                            <input  ref="onSureDiv" className="open-submit" type="button"
                                                   onClick={this.onSureDiv.bind(null,this.state.loginContent)} value="确定"/>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                    </div>
                </div>

                <div style={this.state.openQuDao?styles.openBg:styles.closeBg}>
                    <div className={this.state.openQuDao ? "openDiv" : "closeDiv"} style={styles.openNew}>
                        <div className="open-type">
                            <div className="open-title-box">
                                <h3 className="open-title">渠道更新</h3>
                                <span className="open-closeed" onClick={this.onCloseDivQuDao.bind(null)}>关闭</span>
                            </div>
                            <form method="POST" encType="multipart/form-data">
                                <table className="open-table">
                                    <tr>
                                        <td className="">
                                            上传apk
                                        </td>
                                        <td>
                                            <input ref='open_apkQuDao' className="open-apk" type="file" name="apk"/>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="open-upData-login">
                                            填写更新日志
                                        </td>
                                        <td>
                                        <textarea className="open-textarea" name="" ref="loginContentQuDao" onChange={this.contentLogin.bind(null,"loginContentQuDao")} placeholder="请输入更新日志" id="" rows="10">

                                        </textarea>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td className="open-upData-login">

                                        </td>
                                        <td className="open-upData-button">
                                            <input ref="onSureDivQuDao" className="open-submit" type="button"
                                                   onClick={this.onSureDivQuDao.bind(null,this.state.loginContentQuDao)} value="确定"/>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                    </div>
                </div>

                <div className="component-container">
                    <ul className="generate-ul">
                        <div className="generate-ul-title">应用程序渠道列表 <span className="generate-upData-open" onClick={self.onUpDataOpenQuDao.bind(null)}>+添加渠道更新</span></div>
                        <li>
                            <span className="generate-dateWidth2">渠道id</span>
                            <span className="generate-date generate-dateWidth1">更新时间</span>
                            <span className="generate-date generate-dateWidth2">大小（b）</span>
                            <span className="generate-date generate-dateWidth2">版本号</span>
                            <span className="generate-dataPadd">删除</span>
                            <span className="generate-dataPadd">渠道更新</span>
                        </li>
                        {appGenerate}
                    </ul>
                </div>

            </div>
        )
    }
});

// 将组件插入到网页中指定的位置
React.render(<DemoComponent />, document.getElementById('demo'));
